package com.gome.transactiontree.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.gome.transactiontree.DefaultTransactionManager;
import com.gome.transactiontree.api.TransactionManager;
import com.gome.transactiontree.recovery.TransactionRecoveryTimer;
import com.gome.transactiontree.repository.DefaultTransactionRepository;
import com.gome.transactiontree.repository.TransactionStore;
import com.gome.transactiontree.util.BeanFactoryUtil;

/**
 * 
 * @author haqiaolong
 */
public class TransactionManagerFactoryBean implements FactoryBean<TransactionManager>, InitializingBean, DisposableBean, BeanFactoryAware, BeanPostProcessor {

	private BeanFactoryUtil beanFactoryUtil = new BeanFactoryUtil();
	
	private DefaultTransactionManager transactionManager = new DefaultTransactionManager();
	
	private DefaultTransactionRepository transactionRepository = new DefaultTransactionRepository();
	
	private TransactionStore transactionStore = null;
	
	private TransactionRecoveryTimer transactionRecoveryTimer = new TransactionRecoveryTimer();
	
	@Override
	public void afterPropertiesSet() throws Exception {
		transactionStore.afterPropertiesSet();
			
		transactionRepository.setTransactionStore(transactionStore);
		
		transactionManager.setTransactionRepository(transactionRepository);
		
		transactionRecoveryTimer.setTransactionRepository(transactionRepository);
		transactionRecoveryTimer.afterPropertiesSet();
	}
	
	@Override
	public void destroy() throws Exception {
		transactionStore.destroy();
		transactionRecoveryTimer.destroy();
	}

	@Override
	public TransactionManager getObject() throws Exception {
		return transactionManager;
	}

	@Override
	public Class<?> getObjectType() {
		return TransactionManager.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
	
	@Override
	public void setBeanFactory(BeanFactory bf) throws BeansException {
		beanFactoryUtil.setBeanFactory(bf);
	}
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		beanFactoryUtil.postProcessBeforeInitialization(bean, beanName);
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		beanFactoryUtil.postProcessAfterInitialization(bean, beanName);
		return bean;
	}

	public void setTransactionStore(TransactionStore transactionStore) {
		this.transactionStore = transactionStore;
	}
	
}